<?php

class ValidatorCombinedKey extends sfValidatorSchema
{

	public function __construct($options = array(), $messages = array())
	{
		parent::__construct(null, $options, $messages);
	}

	protected function configure($options = array(), $messages = array())
	{
		$this->addRequiredOption('model');
		$this->addOption('display_column');
		$this->setMessage('invalid', 'La clave primaria ya existe');
	}

	protected function doClean($values)
	{
		$originalValues = $values;
		$table = Doctrine_Core::getTable($this->getOption('model'));

		if (!is_array($values))
		{
			$columns = $this->getOption('column');
			$values = array($columns[0] => $values);
		}

		$table = Doctrine_Core::getTable($this->getOption('model'));
		$keys = $table->getIdentifier();
		$query = $table->createQuery('a');

		foreach ($keys as $key)
		{
			$query->addWhere('a.' . $key . ' = ?', $values[$key]);
		}

		$object = $query->fetchOne();


		if (!$object)
		{
			return $originalValues;
		}

		$error = new sfValidatorError($this, 'invalid', array('column' => implode(', ', $keys)));

		$column = $this->getOption('display_column');
		if ($column === null)
			$column = $keys[0];

		throw new sfValidatorErrorSchema($this, array($column => $error));
	}

}